package com.example.c16b.recentimagesvideosdemo;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class main extends AppCompatActivity {

    private RecyclerView mRecyclerView;
    private HomeAdapter mAdapter;
    private ArrayList<String> mImageArr = new ArrayList<String>();
    public static final String LOG_TAG = "RI&V";
    private static long recentTime = System.currentTimeMillis() / 1000 + 60*60;//最近时间
    private static String DATA = MediaStore.Images.Media.DATA;
    private static String DATE_ADDED = MediaStore.Images.Media.DATE_ADDED;
    private static String ID = MediaStore.Images.Media._ID;
    private static String MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
    private static String SIZE = MediaStore.Images.Media.DATE_ADDED;
    private static String DATE_MODIFIED = MediaStore.Images.Media.DATE_MODIFIED;
    private static Uri EXTERNAL_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    private static final int LOAD_END = 1;
    CoordinatorLayout container;
    private long mExitTime;
    private static int Mode = 0;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initData();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        container = (CoordinatorLayout) findViewById(R.id.cl);
        setSupportActionBar(toolbar);

        Spinner spinner = (Spinner) findViewById(R.id.spinner1);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                long[] times = { System.currentTimeMillis() / 1000 + 60*60,60*60,60*60*24,60*60*24*7 };
                recentTime = times[pos];
                mImageArr.clear();
                initData();
                mAdapter.notifyDataSetChanged();
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });

        final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);

        if (fab != null) {
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (Mode == 0) {
                        fab.setImageResource(android.R.drawable.ic_menu_camera);
                        DATA = MediaStore.Video.Media.DATA;
                        DATE_ADDED = MediaStore.Video.Media.DATE_ADDED;
                        ID = MediaStore.Video.Media._ID;
                        MIME_TYPE = MediaStore.Video.Media.MIME_TYPE;
                        SIZE = MediaStore.Video.Media.DATE_ADDED;
                        DATE_MODIFIED = MediaStore.Video.Media.DATE_MODIFIED;
                        EXTERNAL_CONTENT_URI = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                        Mode = 1;
                        mImageArr.clear();
                        initData();
                        mAdapter.notifyDataSetChanged();
                        Snackbar.make(container, "now show you videos", Snackbar.LENGTH_LONG).show();
                    } else if (Mode == 1) {
                        fab.setImageResource(android.R.drawable.ic_menu_report_image);
                        DATA = MediaStore.Images.Media.DATA;
                        DATE_ADDED = MediaStore.Images.Media.DATE_ADDED;
                        ID = MediaStore.Images.Media._ID;
                        MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
                        SIZE = MediaStore.Images.Media.DATE_ADDED;
                        DATE_MODIFIED = MediaStore.Images.Media.DATE_MODIFIED;
                        EXTERNAL_CONTENT_URI = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                        Mode = 0;
                        mImageArr.clear();
                        initData();
                        mAdapter.notifyDataSetChanged();
                        Snackbar.make(container, "now show you images", Snackbar.LENGTH_LONG).show();
                    }
                }
            });
        }
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                Object mHelperUtils;
                Snackbar.make(container, "press back button again to exit", Snackbar.LENGTH_LONG).show();
                mExitTime = System.currentTimeMillis();
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private Handler loadPicHandle = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case LOAD_END:
                    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview);
                    mRecyclerView.setLayoutManager(new LinearLayoutManager(MyApplication.getContext()));
                    mRecyclerView.setAdapter(mAdapter = new HomeAdapter());
                    break;
                default:
                    break;
            }
        }
    };

    protected void initData() {
        Intent scanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED);
        scanIntent.setData(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath())));
        sendBroadcast(scanIntent);

        Context ctx = main.this;
        ContentResolver contentR = ctx.getContentResolver();
        Cursor cursor = null;
        String[] projection = {ID, MIME_TYPE, DATA, SIZE, DATE_MODIFIED, DATE_ADDED};//要获取的列

        String selection = DATE_ADDED + ">?";
        long arg = System.currentTimeMillis() / 1000 - recentTime;
        String[] selectionArgs = {"" + arg};

        String sortOrder = DATE_ADDED + " desc";//按照时间降序

        try {
            cursor = contentR.query(EXTERNAL_CONTENT_URI, projection, selection,
                    selectionArgs, sortOrder);
            if (null == cursor) {
                Log.d(LOG_TAG, "cursor is null");
            }
            cursor.moveToFirst();

            while (cursor.moveToNext()) {
                String src = cursor.getString(cursor.getColumnIndex(DATA));
                String time = getStrTime(cursor.getString(cursor.getColumnIndex(DATE_ADDED)));

                Log.d(LOG_TAG, "src:" + src);
                Log.d(LOG_TAG, "time:" + time);
                //通过图片的路径加载图片
                mImageArr.add(src);
            }

            if (!mImageArr.isEmpty()) {
                Message msg = Message.obtain();
                msg.what = LOAD_END;
                loadPicHandle.sendMessage(msg);
            }
        } catch (Exception e) {
            Log.e(LOG_TAG, e.getMessage());
        } finally {
            cursor.close();
        }
    }

    public static String getStrTime(String cc_time) {
        String re_StrTime = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
        // 例如：cc_time=1291778220
        long lcc_time = Long.valueOf(cc_time);
        re_StrTime = sdf.format(new Date(lcc_time * 1000L));
        return re_StrTime;
    }

    class HomeAdapter extends RecyclerView.Adapter<HomeAdapter.MyViewHolder> {

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            MyViewHolder holder = new MyViewHolder(LayoutInflater.from(
                    main.this).inflate(R.layout.items, parent,
                    false));
            return holder;
        }


        @Override
        public void onBindViewHolder(MyViewHolder holder, int position) {
            Glide.with(MyApplication.getContext()).load(mImageArr.get(position)).into(holder.iv);
        }

        @Override
        public int getItemCount() {
            return mImageArr.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {
            ImageView iv;

            public MyViewHolder(View view) {
                super(view);
                iv = (ImageView) view.findViewById(R.id.iv);
            }
        }
    }

}
